package com.gec.zhs.controller;

import cn.hutool.core.util.ObjectUtil;
import com.gec.zhs.annotation.ZhsLogin;
import com.gec.zhs.component.RedisComponent;
import com.gec.zhs.entity.constants.Constants;
import com.gec.zhs.entity.dto.TokenUserInfoDto;
import com.gec.zhs.entity.dto.UserCountInfoDto;
import com.gec.zhs.entity.vo.ResponseVO;
import com.gec.zhs.exception.BusinessException;
import com.gec.zhs.service.UserInfoService;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-01-11
 * @description 用户账户
 */
@RestController
@RequestMapping("/account")
public class UserAccountController extends ABaseController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisComponent redisComponent;

    /**
     * 获取验证码，转化成base64的编码再转化成图片
     * @return
     */
    @ApiOperation("登陆/注册的验证码")
    @RequestMapping("/checkCode")
    public ResponseVO verificationCode() {
        //验证码,图片
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 40);
        String code = captcha.text();
        String checkCodeKey = redisComponent.saveCheckCode(code);
        //base64编码
        String checkCode = captcha.toBase64();
        Map<String, Object> map = new HashMap<>();
        map.put("checkCode", checkCode);
        map.put("checkCodeKey", checkCodeKey);
        return getSuccessResponseVO(map);
    }

    @ApiOperation("用户注册")
    @RequestMapping(value = "/register")
    public ResponseVO register(String email,
                               String nickName,
                               String registerPassword,
                               String checkCodeKey,
                               String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))) {
                throw new BusinessException("图片验证码不正确");
            }
            userInfoService.register(email, nickName, registerPassword);
            return getSuccessResponseVO(null);
        } finally {
            redisComponent.deleteCheckCode(checkCodeKey);
        }
    }

    @ApiOperation("用户登陆")
    @RequestMapping(value = "/login")
    public ResponseVO login(HttpServletRequest request,
                            HttpServletResponse response,
                            String email,
                            String password,
                            String checkCodeKey,
                            String checkCode) {
        try {
            if (!checkCode.equalsIgnoreCase(redisComponent.getCheckCode(checkCodeKey))) {
                throw new BusinessException("图片验证码不正确");
            }
            //获取ip
            String ip = getIpAddr();
            TokenUserInfoDto tokenUserInfoDto = userInfoService.login(email, password, ip);
            //往cookie中插入token
            saveTokenToCookie(response, tokenUserInfoDto.getToken());
            return getSuccessResponseVO(tokenUserInfoDto);
        } finally {
            redisComponent.deleteCheckCode(checkCodeKey);
            Cookie[] cookies = request.getCookies();
            //失败了清除掉cookie的token和验证码
            if (cookies != null) {
                String token = null;
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(Constants.TOKEN_WEB)) {
                        token = cookie.getValue();
                    }
                }
                if (StringUtils.hasText(token)) {
                    redisComponent.deleteToken(token);
                }
            }
        }
    }

    @ApiOperation("自动登陆")
    @RequestMapping("/autoLogin")
    public ResponseVO autoLogin(HttpServletResponse response) {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        if (ObjectUtil.isEmpty(tokenUserInfoDto)) {
            throw new BusinessException("没有对应的tokenUserInfoDto");
        }
        //续期
        if (tokenUserInfoDto.getExpireAt() - System.currentTimeMillis() < Constants.TIME_SECONDS_DAY) {
            redisComponent.saveTokenInfo(tokenUserInfoDto);
            saveTokenToCookie(response, tokenUserInfoDto.getToken());
        }
        saveTokenToCookie(response, tokenUserInfoDto.getToken());
        return getSuccessResponseVO(tokenUserInfoDto);
    }

    @ApiOperation("退出")
    @RequestMapping("/logout")
    @ZhsLogin(checkLogin = true)
    public ResponseVO logout(HttpServletResponse response) {
        cleanCookie(response);
        return getSuccessResponseVO(null);
    }


    @ApiOperation("获取用户信息")
    @RequestMapping("/getUserCountInfo")
    @ZhsLogin(checkLogin = true)
    public ResponseVO getUserCountInfo(){
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
        UserCountInfoDto userCountInfo = userInfoService.getUserCountInfo(tokenUserInfoDto.getUserId());
        return getSuccessResponseVO(userCountInfo);
    }
}
